package com.mattgarner.jaddas.node;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class ErrorLogManager {
	private NodeConfigurationManager nodeConfig;
	private static ErrorLogManager instance;
	private BufferedWriter fileOut;
	
	public ErrorLogManager() {
		System.out.println("log instance");
		nodeConfig = NodeConfigurationManager.getInstance();
    	Date now = new Date();
		try {
	        fileOut = new BufferedWriter(new FileWriter(nodeConfig.getErrorLogFile(), true));
	    } catch (IOException e) {
	    	System.out.println("** CRITICAL ** Cannot open log file: " + e.getMessage());
	    	System.exit(-1);
	    }
	    try {
	        fileOut.write(now.toString()+": *** INIT NODE ***\r\n");
	        fileOut.flush();
	    } catch (IOException e) {
	    	System.out.println("** CRITICAL ** Cannot write to log file: " + e.getMessage());
	    	System.exit(-1);
	    }
	}
	
	// singleton method
	public final static ErrorLogManager getInstance() {
		if(instance == null) { 
			instance = new ErrorLogManager();
		}
		return instance;
	}
	
	public final void writeToLog(int debugLevel, String component, String message) {
		Date now = new Date();
		if(debugLevel <= nodeConfig.logDebugLevel) {
			try {
		        fileOut.write(now.toString() + ":" + component + ":" + message + "\r\n");
		        fileOut.flush();
		    } catch (IOException e) {
		    	System.out.println("** ERROR ** Failed write to log file at '"+nodeConfig.getErrorLogFile()+"'");
		    }
		}
		if(debugLevel <= nodeConfig.consoleDebugLevel) {
	    	System.out.println(now.toString() + ":" + component + ":" + message);
	    }
	}
	

}
